#pragma once
#include <iostream>
#include <pthread.h>
#include <queue>

#define DEFAULTVALUE 12

// class Mutex
// {
// public:
//     Mutex(){pthread_mutex_init(&_lock,nullptr);}
//     ~Mutex(){pthread_mutex_destroy(&_lock);}
// private:
//     pthread_mutex_t _lock;
// };
template <class T>
class BlockQueue
{
public:
    BlockQueue(int maxcap = DEFAULTVALUE) : _maxcap(maxcap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_p_cond, nullptr);
        pthread_cond_init(&_c_cond, nullptr);
        _low_water = maxcap / 3;
        _high_water = (maxcap * 2) / 3;
    }
    T pop()
    {
        pthread_mutex_lock(&_mutex);
        while (_q.size() == 0)
        {
            pthread_cond_wait(&_c_cond, &_mutex);
        }
        // 消费
        T out = _q.front();
        _q.pop();
        if (_q.size() <= _low_water)
            pthread_cond_signal(&_p_cond);
        pthread_mutex_unlock(&_mutex);
        return out;
    }
    void push(const T &in)
    {
        pthread_mutex_lock(&_mutex);
        while (_q.size() == _maxcap)
        {
            pthread_cond_wait(&_p_cond, &_mutex);
        }
        _q.push(in);
        if (_q.size() >= _high_water)
            pthread_cond_signal(&_c_cond);
        pthread_mutex_unlock(&_mutex);
    }
    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_c_cond);
        pthread_cond_destroy(&_p_cond);
    }

private:
    pthread_mutex_t _mutex;
    pthread_cond_t _p_cond;
    pthread_cond_t _c_cond;
    std::queue<T> _q;
    int _maxcap;
    int _low_water;
    int _high_water;
};
